// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package menu

import (
	"audio-server/internal/model"
	"context"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuPageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuPageLogic {
	return &MenuPageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuPageLogic) MenuPage(req *types.MenuPageReq) (resp *types.MenuPageRes, err error) {
	pageNum := req.PageNum
	if pageNum <= 0 {
		pageNum = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10
	}

	offset := (pageNum - 1) * pageSize
	menuModel := model.NewMenuModel(l.svcCtx.Conn)
	menuList, err := menuModel.FindMenuPage(l.ctx, offset, pageSize)
	if err != nil {
		return nil, err
	}
	var result []types.MenuRes
	for _, menu := range menuList {
		result = append(result, types.MenuRes{
			MenuId:     int(menu.Id),
			ParentId:   nullInt64ToInt(menu.ParentId),
			Title:      nullStringToString(menu.Title),
			Path:       menu.Path,
			Component:  menu.Component,
			Redirect:   nullStringToString(menu.Redirect),
			Type:       nullInt64ToInt(menu.Type),
			SvgIcon:    nullStringToString(menu.SvgIcon),
			Icon:       nullStringToString(menu.Icon),
			KeepAlive:  int(menu.KeepAlive),
			Hidden:     nullInt64ToInt(menu.Hidden),
			Sort:       nullInt64ToInt(menu.Sort),
			ActiveMenu: nullStringToString(menu.ActiveMenu),
			Breadcrumb: nullInt64ToInt(menu.Breadcrumb),
			ShowInTabs: nullInt64ToInt(menu.ShowInTabs),
			AlwaysShow: nullInt64ToInt(menu.AlwaysShow),
			Affix:      nullInt64ToInt(menu.Affix),
		})
	}
	count, err := menuModel.FindMenuCount(l.ctx)
	return &types.MenuPageRes{Total: count, List: buildMenuTree(result, 0)}, nil
}

func buildMenuTree(menus []types.MenuRes, parentId int) []types.MenuRes {
	var rootMenus []types.MenuRes
	for _, menu := range menus {
		if menu.ParentId == parentId {
			menu.Children = buildMenuTree(menus, menu.MenuId)
			rootMenus = append(rootMenus, menu)
		}
	}
	return rootMenus
}
